//
//  SHENetworkObj.m
//  SHEPuzzleFigure
//
//  Created by SW mini on 2019/11/25.
//  Copyright © 2019 Figure. All rights reserved.
//

#import "SHENetworkObj.h"

@implementation SHENetworkObj

+ (void)postwithUrl:(NSString *)apiUrl success:(nonnull SuccessBlock)successBlock failure:(nonnull FailureBlock)failureBlock{

    NSString *Url = [NSString stringWithFormat:@"%@%@",API_HOST,apiUrl];
    
    NSLog(@"url-%@",Url);
    NSURL *url = [NSURL URLWithString:Url];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//    NSData *httpBody = [[self toJsonData:@[]] dataUsingEncoding:NSUTF8StringEncoding];
//    [request setHTTPBody:httpBody];
    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    [request setHTTPMethod:@"POST"];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:
     ^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
         [EasyLoadingView hidenLoading];
         NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
         long status = (long)httpResponse.statusCode;
         if(status){
             if(![data isKindOfClass:[NSNull class]]){
                 NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
                 dispatch_async(dispatch_get_main_queue(), ^{
                     successBlock(responseDictionary);
                 });
             }else{
                 dispatch_async(dispatch_get_main_queue(), ^{
                     NSDictionary *resultDic = @{@"status":@"-1",@"msg":@"结果异常"};
                     successBlock(resultDic);
                 });
             }
         }else{
             NSLog(@" http response status : %ld",status);
             dispatch_async(dispatch_get_main_queue(), ^{
                 failureBlock(response, connectionError);
             });
         }
     }];
}

+ (NSString *)toJsonData:(NSMutableDictionary *)dict
{
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}




@end
